<template>
  <XhhTable
      ref="table"
      :columns="columns"
      :api="api"
      :form-config="formConfig"
      :params="formConfig.form"
      unique-id="news-list-table"
      is-pagination
      stripe
      checkbox
      :setEditDialog="setEditDialog"
      :setAddDialog="setAddDialog"
      :row-class-name="handleRowClassName"
      @delete="handleDelete"
      @del="handleDel"
      @disableRow="handleDisableRow"
      @enableRow="handleEnableRow"
  ></XhhTable>
</template>
<script setup>
import {ref, reactive, h} from 'vue'
import req from '@/utils/req/axios'
import {tip, tipBox} from '@tip'
import {requiredRule} from '@/utils/common/form'
import urls from '@/utils/constants/urls.js'
import {listBySetCodeApi, showOverflowTooltip} from '@/utils/constants/utils'
import UploadFile from '@/components/common/upload-file.vue'
import {ElButton} from 'element-plus'
import {destName} from '@/utils/common/fns'

const table = ref()
const contentTypeList = [
  {
    id: '1',
    name: '文件类型',
  },
  {
    id: '2',
    name: '富文本类型',
  },
]
const statusList = [
  {
    id: 0,
    name: '草稿',
  },
  {
    id: 1,
    name: '已发布',
  },
  {
    id: 2,
    name: '已下架',
  },
]
const columns = ref([
  {
    prop: 'typeName',
    label: '类型',
    width: 120,
  },
  {
    prop: 'title',
    label: '标题',
    width: 120,
    ...showOverflowTooltip,
  },
  {
    prop: 'summary',
    label: '简介',
    ...showOverflowTooltip,
  },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    formatter(r, c, v) {
      return destName(statusList, v)
    },
  },
  {
    prop: 'createdAt',
    label: '创建时间',
    width: 140,
  },
  {
    prop: 'publishDate',
    label: '发布时间',
    width: 140,
  },
  {
    prop: 'author',
    label: '作者',
    width: 120,
  },
  {
    prop: 'viewCount',
    label: '浏览量',
    width: 90,
  },
  {
    prop: 'op',
    label: '操作',
    buttons({row}) {
      return [
        'delete',
        'view',
      ]
    },
    width: 270,
  },
])
const api = {
  async request(params) {
    const {total, data} = await req.post(urls.v3.news.list, {
      ...params,
      ...(params.status === undefined ? {status: []} : {}),
    })
    return {
      total,
      data,
    }
  },
}
// const contentFileInputRef = ref()
/**
 * status 上传状态，1：初始化：显示未上传文件，2：上传中，显示上传中，3：上传完成，显示文件名
 */
// const contentFile = reactive({fileName: '', fileId: '', status: 1})
const fileId = ref('test1')
const coverImage = ref('test2')
const crtFormMode = ref('view') // view,add,edit
const crtFormData = ref(null)

const formConfig = reactive({
  form: {
    status: [],
  },
  schema: [
    {
      prop: 'title',
      label: '标题',
    },
    {
      prop: 'publishDate',
      label: '发布时间',
      comp: 'ElDatePicker',
      props: {
        'popper-class': 'date-select-popper',
        type: 'daterange',
      },
    },
    {
      prop: 'status',
      label: '状态',
      comp: 'select',
      props: {
        multiple: true,
        options: statusList,
      },
    },
  ],
  queryFormProps: {},
  // 如果配置了dialogForm，则新增按钮会自动弹出
  dialogForm: {},
  dialogSchema: [
    {
      prop: 'type',
      label: '新闻分类',
      comp: 'select',
      props: {
        ...listBySetCodeApi('V3_NEWS_TYPE'),
      },
      colProps: {span: 6},
    },
    {
      prop: 'title',
      label: '标题',
      props: {
        type: 'textarea',
        autosize: {
          minRows: 1,
          maxRows: 3,
        },
      },
      colProps: {span: 18},
    },
    {
      prop: 'summary',
      label: '简介',
      props: {
        type: 'textarea',
        autosize: {
          minRows: 2,
          maxRows: 4,
        },
      },
      colProps: {span: 24},
    },
    {
      prop: 'coverImage',
      label: '封面',
      render() {
        return h(UploadFile, {
          onUploaded(v) {
            coverImage.value = v.fileId
          },
        })
      },
      colProps: {span: 24},
    },
    {
      prop: 'contentType',
      label: '内容类型',
      comp: 'select',
      props: {
        options: contentTypeList,
        // 通过select切换表单项的显示隐藏
        onChange(val) {
          const contentTextItem = formConfig.dialogSchema.find(item => item.prop === 'content')
          const contentFileItem = formConfig.dialogSchema.find(item => item.prop === 'fileId')
          if (val === '1') {
            contentTextItem.colProps.class = 'dni'
            contentFileItem.colProps.class = ''
          } else if (val === '2') {
            contentTextItem.colProps.class = ''
            contentFileItem.colProps.class = 'dni'
          }
        },
      },
      colProps: {span: 6},
    },
    // 默认隐藏，当 contentType 选择 指定值时，再显示
    {
      prop: 'content',
      label: '富文本内容',
      colProps: {span: 24, class: 'dni'},
      // 富文本编辑器
      // todo富文本配置
      type: 'textarea',
      placeholder: '富文本暂未实现...',
      autosize: {
        minRows: 3,
        maxRows: 6,
      },
    },
    {
      prop: 'fileId',
      label: '文件内容',
      colProps: {span: 24, class: 'dni'},
      render() {
        return h(UploadFile, {
          onUploaded(v) {
            fileId.value = v.fileId
          },
        })
      },
      // 使用render渲染自定义内容
      // 上传文件
      // render() {
      //   return h('div', {
      //     class: 'app-upload-wrap',
      //   }, [
      //     h(ElButton, {
      //       type: 'primary',
      //       onClick() {
      //         console.log('获取ref', contentFileInputRef)
      //         contentFileInputRef.value.click()
      //       },
      //     }, () => '选择文件'),
      //     h('input', {
      //       hidden: true,
      //       ref: contentFileInputRef,
      //       type: 'file',
      //       onChange(e) {
      //         console.log('change file', e)
      //         const file = e.target.files[0]
      //         if (file) {
      //           console.log('选中的文件：', file)
      //           // 准备上传
      //           contentFile.fileName = file.name
      //         }
      //       },
      //     }),
      //     h('span', {
      //       class: 'app-upload-file-name',
      //       onClick() {
      //         console.log('打开新页面，查看/下载文件')
      //       }
      //     }, contentFile.fileName),
      //     h(ElIcon, {
      //       class: 'app-upload-file-close',
      //       onClick() {
      //         console.log('click close')
      //       },
      //     }, () => [h(CircleClose)]),
      //   ])
      // },
    },
  ],
  dialogFormProps: {
    rules: {
      ...requiredRule('title'),
    },
  },
  dialogSlots: {},
  dialogProps: {
    fullscreen: true,
    async onConfirm() {
      // todo 验证表单
      console.log('table', table)
      const valid = await table.value.instance.refs.dialogFormRef.validate()
      if (!valid) {
        return
      }
      // await table.value.validDialogForm()
      // 如果验证失败，直接就在内部抛出错误了，下边的代码不会走了
      // 获取表单数据
      // 整理表单数据
      let url
      // 发送请求
      if (table.value.dialogFormMode === 'add') {
        // 新增
        url = urls.v3.news.add
      } else if (table.value.dialogFormMode === 'edit') {
        // 编辑
        url = urls.v3.news.update
      }
      console.log('表单数据：', table.value.dialogForm)
      // 表单中的所有属性都将作为参数拼接在sql中，所以页面中自定义的字段不能放在params中
      // const form = table.value.dialogForm
      const {contentType, ...params} = table.value.dialogForm
      params.fileId = '8CFdNgOeL7EYoB4V' // fileId.value
      params.coverImage = coverImage.value
      // const params = {
      //   title: form.title,
      //   type: form.type,
      //   summary: form.summary,
      //   ...(form.contentType === '1' ? {fileId: contentFile.value} : {}),
      //   ...(form.contentType === '2' ? {content: form.content} : {}),
      //   ...(coverImage.value ? )
      // }
      // 表单数据
      // const params = {
      //   ...table.value.dialogForm,
      // }
      await req.post(url, params)
      // 关闭弹窗
      table.value.closeFormDialog()
      // 刷新列表
      table.value.searchData(true)
    },
  },
})
const cancelButton = h(ElButton, {
  onClick() {
    table.value.closeFormDialog()
  },
}, () => '取消')
const editButton = h(ElButton, {
  onClick() {
    crtFormMode.value = 'edit'
    // 下一个版本会更新 updateDialogFormMode 方法，用此方法进行更新 table.value.updateDialogFormMode('edit')
    table.value.dialogFormMode = 'edit'
    formConfig.dialogSlots = getFooterSlot()
  },
}, () => '编辑')
const publishButton = h(ElButton, {}, () => '发布')
const cancelPublishButton = h(ElButton, {}, () => '下架')
const rePublishButton = h(ElButton, {}, () => '重新发布')

const saveDraftButton = h(ElButton, {}, () => '保存为草稿')
const savePublishButton = h(ElButton, {}, () => '保存并发布')

function getFooterSlot() {
  return {
    footer: () => {
      return h('div', {}, [
        cancelButton,
        ...(crtFormMode.value === 'view' ? [
          editButton,
          ...(crtFormData.value.status === 0 ? [
            publishButton,
          ] : crtFormData.value.status === 1 ? [
            cancelPublishButton,
          ] : crtFormData.value.status === 2 ? [
            rePublishButton,
          ] : []),
        ] : crtFormMode.value === 'edit' ? [
          ...(crtFormData.value.status === 0 ? [
            saveDraftButton,
            savePublishButton,
          ] : crtFormData.value.status === 1 ? [] : crtFormData.value.status === 2 ? [
            rePublishButton,
          ] : []),
        ] : crtFormMode.value === 'add' ? [
          saveDraftButton,
          savePublishButton,
        ] : []),
      ])
    },
  }
}

function setAddDialog({props}) {
  crtFormMode.value = 'add'
  crtFormData.value = null
  formConfig.dialogSlots = getFooterSlot()
}

function setEditDialog({props, scope}) {
  console.log('编辑的当前数据：', scope.row)
  crtFormMode.value = 'view'
  crtFormData.value = scope.row
  formConfig.dialogSlots = getFooterSlot()
  // 下个版本通过 updateDialogForm 更新
  props.dialogForm.value = scope.row
}

/**
 * 单个删除
 * @param row
 * @returns {Promise<void>}
 */
async function handleDelete({row}) {
  await req.post(urls.v3.news.del, {id: row.id})
  table.value.searchData(true)
}

/**
 * 批量删除
 * @returns {Promise<void>}
 */
async function handleDel() {
  if (!table.value.checkedRows?.length) {
    tip({message: '请选择要删除的行', type: 'error'})
    return
  }
  await req.post(urls.v3.news.del, {
    ids: table.value.checkedRows.map((item) => item.id),
  })
  table.value.searchData()
}

async function handleStatusRow({row, status, message, label}) {
  const confirm = await tipBox.confirm(`确认要执行${label}操作吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  if (confirm === 'confirm') {
    await req.post(urls.v3.news.update, {id: row.id, status}, {_showSuccessTip: false})
    tip({message, type: 'success'})
    table.value.searchData(true)
  }
}

async function handleDisableRow({row}) {
  await handleStatusRow({row, status: '2', message: '停用成功', label: '停用'})
}

async function handleEnableRow({row}) {
  await handleStatusRow({row, status: '1', message: '启用成功', label: '启用'})
}

function handleRowClassName({row}) {
  return row.status === '1' ? 'enable-row' : 'disable-row'
}
</script>
<style lang="less">
.date-select-popper {
  .el-picker-panel__sidebar {
    width: 150px;
  }

  .el-picker-panel [slot='sidebar'] + .el-picker-panel__body,
  .el-picker-panel__sidebar + .el-picker-panel__body {
    margin-left: 150px;
  }
}
</style>
